<?php

namespace app\company\model;


use app\admin\model\Goods;
use app\admin\model\GoodsRule;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use app\admin\model\CompanyOrderLog;

/**
 * @property  int $id
 * @property  string $no 订单号
 * @property  int $company_id 公司id
 * @property  int $order_status  订单状态 状态 1:待审核,2:待签收,3:待上架,4:审核拒绝,5:已完成
 * @property  int $company_user_id  用户ID
 * @property  string $remark  备注
 * @property  int $goods_rule_id
 * @property  int $goods_id
 * @property  int $supplier_id
 */
class CompanyOrder extends Base
{

    public static function onBeforeInsert(CompanyOrder $model)
    {
        // 订单号  规则：CG+年月日+6位随机数
        $model->no              = 'CG' . date('Ymd') . rand(10000, 99999);
        $model->company_id      = getCompanyId();
        $model->company_user_id = getCompanyUserId();
    }

    /**
     * 添加事件
     * @param CompanyOrder $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public static function onAfterInsert(CompanyOrder $model): void
    {
        $param = request()->param();
        $array = [];
        foreach ($param['rules'] as $key => $value) {
            if (!$rule = GoodsRule::where('id', $value['goods_rule_id'])->withTrashed()->find()) exception("产品不存在");
            // 前端如果传入价格就以传入为准，没传就以查询为主
            if(isset($value['purchasing_price']) && $value['purchasing_price'] > 0){
                $rule->purchasing_price = $value['purchasing_price'];
            }
            $array[$key]['company_id']       = $model->company_id;
            $array[$key]['goods_id']         = $rule->goods_id;
            $array[$key]['goods_rule_id']    = $rule->id;
            $array[$key]['goods_cate_id']    = Goods::where('id', $rule->goods_id)->withTrashed()->value('goods_cate_id');
            $array[$key]['quantity']         = $value['quantity'];
            $array[$key]['amount']           = $value['quantity'] * $rule->purchasing_price;
            $array[$key]['money']            = $rule->money;
            $array[$key]['purchasing_price'] = $rule->purchasing_price;
            $array[$key]['company_order_id'] = $model->id;

            // 推断最近一次的经销商
            $supplier_id = CompanyOrderDetail::where('company_id', $model->company_id)
                                             ->goodsRuleId($value['goods_rule_id'])->order('id desc')->value('supplier_id');

            $array[$key]['supplier_id'] = $supplier_id;
        }
        if (!$array) exception("请选择产品");
        (new CompanyOrderDetail())->saveAll($array);
        //添加订单日志
        (new CompanyOrderLog)->add($model->id, 1, $model->remark);
    }

    /**
     * 更新前
     * @param CompanyOrder $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeUpdate(CompanyOrder $model): void
    {
        $param = request()->param();
        if (request()->param('order_status', 0)) {
            //签收 奇怪的需求,签收之后还可以继续进行签收
//            if ($model->order_status == 3 && $model->getOrigin('order_status') != 2) exception("订单状态异常,无法签收");
            //完成
            if ($model->order_status == 5 && $model->getOrigin('order_status') != 3) exception("订单状态异常,无法完成");
            //添加订单日志
            (new CompanyOrderLog)->add($model->id, $model->order_status, $model->remark);

            //上架
            if ($model->order_status == 5 && $model->getOrigin('order_status') == 3) {
                if ($model->companyOrderStorages()->sum('quantity') != $model->companyOrderDetails()->sum('quantity')) exception("订单未分配库位,无法上架");
                if ($model->companyOrderDetails()->where('production_time', 0)->count()) exception("订单未填写生产日期,无法上架");
                //更新订单库位详情表,更新后这个数据才能被读取消费使用
                $model->companyOrderStorages->update(['status' => 1, 'active_time' => time()]);

                //库存上redis
                $key1 = kcGoodsRuleKey() . $model->company_id;//商品规格
                $key2 = kcGoodsKey() . $model->company_id;//商品
                $model->companyOrderStorages()->select()->each(function ($item) use ($key1, $key2) {
                    redis()->zincrby($key1, $item->quantity, $item->goods_rule_id);//创建有序集合 并累加
                    redis()->zincrby($key2, $item->quantity, $item->goods_id);//创建有序集合 并累加
                });
                $model->companyOrderDetails()->select()->each(function ($item) {
                    //判断当前公司有没有这个商品规格,如果没有则添加
                    if (!CompanyGoodsRule::where('company_id', $item->company_id)->where('goods_rule_id', $item->goods_rule_id)->find()) {
                        $companyGoodsRule                = new CompanyGoodsRule();
                        $companyGoodsRule->company_id    = $item->company_id;
                        //此时需求是 公司和供应商是一对一的关系,不会变更, 后期如变更再从其他方式修改 此对应关系已废弃
                        $companyGoodsRule->supplier_id   = $item->supplier_id;
                        $companyGoodsRule->goods_id      = $item->goods_id;
                        $companyGoodsRule->goods_rule_id = $item->goods_rule_id;
                        $companyGoodsRule->money         = $item->goodsRule()->value('money');//售价
                        $companyGoodsRule->save();
                    };
                    //判断当前公司有没有这个商品,如果没有则添加
                    if (!CompanyGoods::where('company_id', $item->company_id)->where('goods_id', $item->goods_id)->find()) {
                        $goodsInfo                   = $item->goods()->find();
                        $companyGoods                = new CompanyGoods();
                        $companyGoods->company_id    = $item->company_id;
                        $companyGoods->goods_id      = $goodsInfo->id;
                        $companyGoods->goods_cate_id = $goodsInfo->goods_cate_id;
                        $companyGoods->descriptions  = $goodsInfo->descriptions;
                        $companyGoods->save();

                        //添加商品默认费率
                        CompanyGoodsRate::create(['goods_id' => $goodsInfo->id, 'company_id' => $item->company_id]);
                    };
                });
                //记录商品出入库日志 必须先执行  //判断当前公司有没有这个商品规格,如果没有则添加
                $model->companyOrderStorages()->select()->each(function ($item) {
                    (new WarehouseStorageGoodsLogs)->companyAdd($item);
                });

            }
        }
    }


    /**
     * @param CompanyOrder $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeDelete(CompanyOrder $model): void
    {
        if ($model->order_status == 5) exception("订单已完成，无法删除");
        $model->companyOrderDetails->delete();
        if ($model->companyOrderStorages()->count()) $model->companyOrderStorages->delete();
    }
}